package com.gudong.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gudong.model.except.ApplicationException;
import com.gudong.model.user.request.wx.WxFindRequest;
import com.gudong.model.user.request.wx.WxLoginRequest;
import com.gudong.user.client.WxClient;
import com.gudong.user.entity.UserInfo;
import com.gudong.user.mapper.UserInfoMapper;
import com.gudong.user.service.IUserInfoService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hl
 * @since 2025-03-05
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Resource
    private WxClient wxClient;

    @Override
    public String wxLogin(WxLoginRequest request) {
        //调用远程微信登录
//        WxLoginResponse wxLoginResponse = wxClient.wxLogin(request.getCode());
//        UserInfo userInfo = baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
//                .eq(UserInfo::getUserWxId, wxLoginResponse.getOpenid()));
        //用户不存在，新增用户信息
//        if (userInfo == null){
//            UserInfo   userInfo = new UserInfo();
//            userInfo.setUserWxId(wxLoginResponse.getOpenid());
//            userInfo.setUserName(request.getUserWxName());
//            userInfo.setType(1);
//            baseMapper.insert(userInfo);
//        }
        UserInfo userInfo = baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserWxId, request.getUserWxId()));
        if (userInfo == null) throw new ApplicationException("用户不存在");
        //生成token

        StpUtil.login(userInfo.getId());
        return StpUtil.getTokenValue();
    }

    /**
     * 查找用户
     *
     * @param request 请求参数
     */
    @Override
    public Page<UserInfo> findUser(WxFindRequest request) {
        return baseMapper.pageList(request.toPage(), request);
    }
}
